package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.domain.Activity;
import com.crm.domain.Contract;
import com.crm.domain.Course;
import com.crm.domain.DictData;
import com.crm.mapper.ContractMapper;
import com.crm.service.ActivityService;
import com.crm.service.ContractService;
import com.crm.service.CourseService;
import com.crm.service.DictDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Slf4j
@Service
public class ContractServiceImpl extends ServiceImpl<ContractMapper, Contract> implements ContractService {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private DictDataService dictDataService;

    public static final String ACTIVITY_TYPE="课程折扣";

    @Override
    public void saveContract(Contract contract) {
        log.info("保存合同信息");
        long courseId = contract.getCourseId();
        Course course = courseService.getById(courseId);
        BigDecimal price = course.getPrice();
        contract.setCoursePrice(price);
        contract.setCreateTime(LocalDateTime.now());

        Integer activityId = contract.getActivityId();
        if (activityId != null) {
            Activity activity = activityService.getById(activityId);
            String typeValue = activity.getType();

            LambdaQueryWrapper<DictData> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DictData::getDictType, "channel_type")
                    .eq(DictData::getDictValue, typeValue);
            DictData dictData = dictDataService.getOne(queryWrapper);
            log.info("设置优惠类型值");
            String dictLabel = dictData.getDictLabel();
            contract.setDiscountType(dictLabel);
            log.info("设置优惠金额");
            if (ACTIVITY_TYPE.equals(dictLabel)){
                contract.setOrder(price.multiply(activity.getDiscount()));
            }else {
                contract.setOrder(price.subtract(activity.getDiscount()));
            }
            //TODO 合同状态，创建人，部门id



        }



    }
}
